var status = 1
var type = true
var tableData = []
var timesDate = getFamtterTimer()
var onceRequestTAG = false;  // 判断是否可查字典表
if (sessionStorage.getItem('UsageAudit_curr') != null) {
    sessionStorage.setItem('UsageAudit_curr',1)
}
function saveTableAudit() {
    let results = sendAjax(modelURL + "system/serviceOption", "POST", {
        userNo: portaluserno,
    });
    if (results.code == 200) {
        tableData = results.data.map(item => {
            return Object.assign(item, {
                APPLICATION_TYPE: '专题应用'
            })
        })
    } else {
        layer.msg('获取失败')
    }
    tables()
    let resultsData = results.data
    let waitCountNum = 0
    for (let i = 0; i < resultsData.length; i++) {
        if (resultsData[i].CHECKSTATUS == '待审核') {
            waitCountNum++
        }
    }
    $('#allCount').html(tableData.length + '个')
    $('#waitCount').html(waitCountNum + '个')
    $('#Count').html(tableData.length - waitCountNum + '个')
    table.on('tool(audit_table)', function (obj) {
        if (obj.event == 'audits') {
            $('#auditsDivH3').html(obj.data.LAYERALIAS)
            $('#applicant').val(obj.data.OWNER)
            let times = formatDate (obj.data.CHECKTIME) // new Date(obj.data.CHECKTIME).toISOString().replace("T", " ").replace(".000Z", "");
            $('#applicantTime').val(times)
            $('#authorizationTime').val('2099-09-15 10:11:12')
            layer.open({
                type: 1,
                title: "审核",
                shadeClose: true,
                content: $('#auditsDiv'),
                end: function (res) {
                    $("#auditsDiv").css("display", 'none');
                },
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    console.log(type, status);
                    if ($('#authorizationReason').val() != '') {
                        type = true
                    }
                    let params = [{
                        checkTime: timesDate,
                        checkPerson: $('#applicant').val(),
                        checkResult: status, // tongguo 1 不通過2 
                        myId: obj.data.ID,
                        checkInfo: $('#authorizationReason').val(),
                        TREEID: obj.data.TREEID,
                        ZYLX: obj.data.ZYLX,
                    }]
                    if (type) {
                        // maps: [{"checkTime":"2021-9-17 16:32:32","checkPerson":"管理员","checkResult":"1","myId":"ddFDbDEA2fDa40EB8Bd388edC55DBCe4","checkInfo":"123","TREEID":"c45d5db988514740829c05d9c2e98b80","ZYLX":"3"}]
                        let results = sendAjax(modelURL + "/resource/saveCheckResult", "POST", {
                            maps: JSON.stringify(params)
                        });
                        if (results.code == 200) {
                            layer.msg(results.msg)
                            saveTableAudit()
                            layer.close(index);
                        } else {
                            layer.msg('获取失败')
                        }
                    } else {
                        layer.msg('请填写审核意见')
                    }

                    // 通过 1
                    // 不通过 2 强制写理由 请填写审核意见 
                },
                btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        } else if (obj.event == 'auditRecords') {
            $('#auditsDivH3').html(obj.data.LAYERALIAS)
            $('#auditRecordsH3').html(obj.data.LAYERALIAS)
            if (obj.data.ZYLX == "1") {
                $('#auditRecordsSH').html('arcgis服务')
            } else if (obj.data.ZYLX == "2") {
                $('#auditRecordsSH').html('arcgis服务子图层')
            } else if (obj.data.ZYLX == "3") {
                $('#auditRecordsSH').html('服务注册')
            } else if (obj.data.ZYLX == "4") {
                $('#auditRecordsSH').html('图件服务')
            }
            $('#auditRecordsTime').html(timesDate)
            $('#auditRecordsYJ').html(obj.data.CHECKINFO)
            $('#auditRecordsJL').html(obj.data.CHECKRESULT)
            layer.open({
                type: 1,
                title: "审核记录",
                shadeClose: true,
                content: $('#auditRecordsDiv'),
                end: function (res) {
                    $("#auditRecordsDiv").css("display", 'none');
                },
                btn: ['取消'],
                yes: function (index, layero) {
                    layer.close(index);
                }
            });
        } else if (obj.event == 'browse') {
            var resourceId = obj.data.RESOURCEID;
            window.open("/MapServer/Portal/layerViewer.html?id=" + resourceId);
        } else if (obj.event == 'download') {

        } else if (obj.event == 'call') {
            $('#serverAddress').val(obj.data.ADDRESS)
            layer.open({
                type: 1,
                title: "调用",
                shadeClose: true, //点击遮罩关闭
                area: ["500px", "200px"],
                content: $("#usedContent"),
                btn: ['关闭'],
                yes: function (index, layero) {
                    layer.close(index);
                }
            });
        }
    })
    table.on('toolbar(audit_table)', function (obj) {
        if (obj.event == 'btn_search') {
            let timeNum = $('#ipt_date').val()
            let startTime = $.trim(timeNum.substring(0, 10));
            let endTime = $.trim(timeNum.substring(13));
            let num
            if ($('#resourceType').val() == 'arcgis服务') num = 1
            if ($('#resourceType').val() == '地图服务') num = 3
            if ($('#resourceType').val() == '图件服务') num = 4
            let results = sendAjax(modelURL + "system/serviceOption", "POST", {
                startTime,
                endTime,
                applyPerson: $('#theApplicant').val(),
                name: $('#applicationName').val(),
                userNo: portaluserno,
                shType: $('#reviewType').val(),
                resourceType: num,
            });
            /*
                String checkresult,
            String userNo,
                String shType, 1
                String resourceType, 2
            String startTime,
            String endTime,
            String applyPerson,
            String name
            */
            if (results.code == 200) {
                tableData = results.data
                sessionStorage.setItem('UsageAudit_curr', 1)
                tables()
            }
        } else if (obj.event == 'btn_reset') {
            sessionStorage.setItem('UsageAudit_curr', 1)
            $('#reviewType').val('')
            $('#resourceType').val('')
            $('#ipt_date').val('')
            $('#theApplicant').val('')
            $('#applicationName').val('')
            saveTableAudit()
        }
    })
}

function resultFunction(obj) {
    let results
    results = sendAjax(modelURL + "/apply/getApplyInfo", "POST", {
        id: obj.data.ID
    });
    return results
}
// 时间戳转换时间函数 
function getYMDHMS(timestamp) {
    let time = new Date(timestamp)
    let year = time.getFullYear()
    const month = (time.getMonth() + 1).toString().padStart(2, '0')
    const date = (time.getDate()).toString().padStart(2, '0')
    const hours = (time.getHours()).toString().padStart(2, '0')
    const minute = (time.getMinutes()).toString().padStart(2, '0')
    const second = (time.getSeconds()).toString().padStart(2, '0')

    return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
// 时间排序
function creatCompare(propertyName) {
    return function (obj1, obj2) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if (value1 > value2) {
            return -1
        } else if (value1 < value2) {
            return 1
        } else {
            return 0
        }
    }
}

function tables() {
    var name = $('#reviewType').val()
    var dateTime = $('#ipt_date').val()
    var theApplicantName = $('#resourceType').val()
    var theApplicant = $('#theApplicant').val()
    var applicationName = $('#applicationName').val()
    tableData.sort(creatCompare("CHECKTIME"))
    var newTableData = tableData.map(item => {
        return Object.assign({}, item, {
            applyTime: getYMDHMS(item.CHECKTIME),
            newCHECKINFO: item.CHECKINFO == "" ? '无' : item.CHECKINFO
        })
    })
    table.render({
        elem: '#audit_table',
        data: newTableData,
        toolbar: true,
        toolbar: '#headerDiv',
        defaultToolbar: [],
        page: {
            limit: 20,
            curr: sessionStorage.getItem('UsageAudit_curr') ? sessionStorage.getItem('UsageAudit_curr') : 1
        },
        done: function (res, curr, count) {
            sessionStorage.setItem('UsageAudit_curr', curr);
            $("[data-field = 'LAYERALIAS']").children().each(function () {
                if($(this).text() != "资源名称"){
                    $(this).addClass("linkTabTxt");
                }
            });
        },
        cols: [
            [ //表头
                {
                    type: 'numbers',
                    title: '序号',
                    sort: true,
                    width: 80,
                    align: "center"
                }, {
                    field: 'LAYERALIAS',
                    title: '资源名称',
                    align: "center"
                }, {
                    title: '资源类型',
                    align: "center",
                    toolbar: '#typeLX',
                }, {
                    field: 'OWNER',
                    title: '申请人',
                    align: "center"
                }, {
                    field: 'applyTime',
                    title: '申请时间',
                    align: "center"
                }, {
                    field: 'newCHECKINFO',
                    title: '申请理由',
                    align: "center"
                },
                //  {
                //     field: 'DANGQIAN',
                //     title: '当前权限',
                //     toolbar: '#currentPermissions',
                //     align: "center"
                // }, 
                {
                    field: 'permission',
                    title: '操作',
                    toolbar: '#permissionAuditDiv',
                    align: "center"
                }
            ]
        ]
    });
    if (name != undefined || dateTime != undefined || theApplicantName != undefined || theApplicant != undefined || applicationName != undefined) {
        $('#reviewType').val(name)
        $('#ipt_date').val(dateTime)
        $('#resourceType').val(theApplicantName)
        $('#theApplicant').val(theApplicant)
        $('#applicationName').val(applicationName)
        layui.form.render('select')
    }
    laydate.render({
        elem: '#ipt_date',
        type: 'date',
        range: true
    });
    $('.layui-table-cell').click(function (e) {
        let text = e.target.innerText
        let currentData = null
        newTableData.map(item => {
            if (text == item.NAME) {
                currentData = item
                return
            }
        })
        if (currentData != null) {
            // getArcgisLayersInfoByGuid(String guid) arcgis服务  RESOURCEID
            // /resource/getResourceByGuid guid  图鉴服务 地图服务 
            let results = null
            if (currentData.ZYLX == 1 || currentData.ZYLX == 2) { 
                results = sendAjax(modelURL + "resource/getArcgisLayersInfoByGuid", "POST", {
                    guid: currentData.RESOURCEID
                });
                let data = results.data 
                for (var key in data) {
                    data = data[key];
                    break;
                }
                var isqueryVal;
                if (data.ISQUERY == "是" || data.ISQUERY == "1") {
                    isqueryVal = "是";
                } else {
                    isqueryVal = "否";
                }
                if (!onceRequestTAG) {
                    fillLayerDropdown('ipt_form_select',data);
                }
                //地图服务数据表单回显
                form.val('MapServiceBasicdataForm', {
                    "LAYERALIAS": data.LAYERALIAS,
                    // "COMPANY": data.COMPANY,
                    // "SPATIAL": data.SPATIAL,
                    // "SERVICESTYPE": data.SERVICE_CATEGORY,
                    // "RESOURCEPOSITION": data.POSITION,
                    "ADDRESS": data.ADDRESS,
                    // "ID": data.ID,
                    "STYLE": data.STYLE,
                    "POSITION": data.LAYERPOSITION,
                    "PRJ": data.PRJ,
                    "PARAMETERS": data.PARAMETERS,
                    // "SERVICETYPE": data.SERVICETYPE,
                    // "SOURCE": data.SOURCE,
                    // "STATUS": data.STATUS,
                    "ISQUERY": isqueryVal,
                    // "SERVERTYPE": data.SERVERTYPE,
                    "YEAR": data.YEAR,
                    "ZYTB": data.ZYTB
                });
            } else {
                results = sendAjax(modelURL + "resource/getResourceByGuid", "POST", {
                    guid: currentData.RESOURCEID
                });
                let data = results.data 
                for (var key in data) {
                    data = data[key];
                    break;
                }
                var isqueryVal;
                if (data.ISQUERY == "是" || data.ISQUERY == "1") {
                    isqueryVal = "是";
                } else {
                    isqueryVal = "否";
                }
                if (!onceRequestTAG) {
                    fillLayerDropdown('ipt_form_select',data);
                }
                //地图服务数据表单回显
                form.val('MapServiceBasicdataForm', {
                    "LAYERALIAS": data.LAYERALIAS,
                    // "COMPANY": data.COMPANY,
                    // "SPATIAL": data.SPATIAL,
                    // "SERVICESTYPE": data.SERVICE_CATEGORY,
                    // "RESOURCEPOSITION": data.POSITION,
                    "ADDRESS": data.ADDRESS,
                    // "ID": data.ID,
                    "STYLE": data.STYLE,
                    "POSITION": data.LAYERPOSITION,
                    "PRJ": data.PRJ,
                    "PARAMETERS": data.PARAMETERS,
                    // "SERVICETYPE": data.SERVICETYPE,
                    // "SOURCE": data.SOURCE,
                    // "STATUS": data.STATUS,
                    "ISQUERY": isqueryVal,
                    // "SERVERTYPE": data.SERVERTYPE,
                    "YEAR": data.YEAR,
                    "ZYTB": data.ZYTB
                });
            }
            if (typeof results == 'string') {
                data = JSON.parse(results).data
            } else {
                data = results.data
            }
            if (currentData.ZYLX == 1 || currentData.ZYLX == 2) { // arcgis服务 
                layer.open({
                    type: 1,
                    title: "arcgis服务详细信息",
                    shadeClose: true,
                    area:['400px','500px'],
                    content: $('#arcgisDiv'),
                    end: function (res) {
                        $("#arcgisDiv").css("display", 'none');
                    },
                    btn: ['确定'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });

            } else if (currentData.ZYLX == 3) { // 服务注册
                layer.open({
                    type: 1,
                    title: "服务注册详细信息",
                    shadeClose: true,
                    area:['400px','500px'],
                    content: $('#regiesterDiv'),
                    end: function (res) {
                        $("#regiesterDiv").css("display", 'none');
                    },
                    btn: ['确定'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });
            } else if (currentData.ZYLX == 4) { // 图件服务 
                layer.open({
                    type: 1,
                    title: "图件服务详细信息",
                    shadeClose: true,
                    area:['400px','500px'],
                    content: $('#mapDiv'),
                    end: function (res) {
                        $("#mapDiv").css("display", 'none');
                    },
                    btn: ['确定'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });
            }
        }
    })
}
//填充图层字段下拉框
function fillLayerDropdown(className,data) {
    var layerSelects = $("." + className);
    var oneSelect, oneSelectName, zdName, dataDict;
    for (var i = 0; i < layerSelects.length; i++) {
        oneSelect = layerSelects[i];
        oneSelectName = oneSelect.attributes.name.value;
        if (oneSelectName == "SPATIAL") {
            zdName = "spatial";
            let dataDict1= getDataDict(zdName); 
            let spatialData = dataDict1.filter (item => item.ZDVALUE == data.SPATIAL)
            $(oneSelect).empty();
            $(oneSelect).val(spatialData[0].ZDTITLE)
        } else if (oneSelectName == "SERVICESTYPE") {
            dataDict = getDataDict("serviceType"); 
            let servarData = dataDict.filter(item => item.ZDVALUE == data.SERVICE_CATEGORY)
            $(oneSelect).val(servarData[0].ZDTITLE)
        } else if (oneSelectName == "RESOURCEPOSITION") {
            var strPositionData = null;
            strPositionData = getSpecialDataDict("position");
            $(oneSelect).empty();
            let positionData = strPositionData.filter(item => item.ID == data.POSITION)
            $(oneSelect).val(positionData[0].ZDTITLE)
        } else if (oneSelectName == "COMPANY") {
            var strCompanyData = null;
            strCompanyData = getCompanyDataDict(portaluserno); 
            $(oneSelect).empty();
            $(oneSelect).val(strCompanyData.FK_DEPTTEXT)
        } else {
            zdName = "layer" + oneSelectName.toLowerCase();
            dataDict = getDataDict(zdName);
            if (zdName == 'layerservicetype') {
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.SERVICETYPE) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } else if (zdName == 'layersource') {
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.SOURCE) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } else if (zdName == 'layerstatus') { 
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.STATUS) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } else if (zdName == 'layerservertype') { 
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.SERVERTYPE) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } 
        } 
    }
    form.render();
    onceRequestTAG = true;
}

function sendAjax(url, type, data) {
    $.ajaxSettings.async = false;
    var results;
    $.ajax({
        type: type,
        dataType: "json",
        url: url,
        data: data,
        success: function (data) {
            results = data;
        },
        error: function (error) {
            results = error;
        }
    });
    return results;
}

function saveRadio() {
    form.on('radio(jiedian)', function (data) {
        if (data.value == '通过') {
            type = true
            status = 1
        } else if (data.value == '不通过') {
            type = false
            status = 2
        }
    })
}